<?php
namespace app\admin\controller;

use think\Controller;
use think\Cookie;
use think\Exception;
use think\Log;
use think\Db;

class Login extends  Controller
{
    public function __construct()
    {
        parent::__construct();
        if(session("admin")||cookie("admin")){
            session("admin",cookie("admin"));
            $this->redirect('Index/index');
        }
    }

    public function index()
    {
        return view("login");
    }
    public function quanxian(){
        return view("/quanxian");
    }
    /**
     * 登录
     * @author wcy
     * @version 2017年4月19日14:20:54
     */
    public function login(){
        try{
            $username=$_POST["username"];
            $password=md5($_POST["password"]);
            $code=$_POST["code"];
            if(!captcha_check($code)){
                return json(["code"=>-1,"msg"=>"验证码错误"]);
            }
            $data=Db::table("user")->where("username='$username' and password='$password' ")->find();
            if($data){
                if(!empty($_POST["online"])){
                   //cookie保存一周
                    cookie("admin",$data,60*60*24*7);
                }
                //单点登录
                $user_code["username"]=$data["username"];
                $user_code["status"]=1;
                $user_code["code"]=time().rand(10000000,99999999);
                $user_code["addtime"]=date("Y-m-d H:i:s",time());
                session("admin",$data);
                return json(["code"=>1,"msg"=>"登录成功"]);
            }else{
                return json(["code"=>-1,"msg"=>"账号或密码错误"]);
            }
        }catch (Exception $e){
            Log::record($e->getMessage());
            return json(["code"=>-1,"msg"=>"登录失败"]);
        }
    }
}